package tiled.simple.gwt.client;

import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;
import org.jbox2d.dynamics.World;

import tiled.simple.core.MapObject;

import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.dom.client.ImageElement;
import com.google.gwt.user.client.ui.Image;

public class RedBall implements Entity {
	private Body body;
	private int r=0;
	
	public RedBall(World world, MapObject mapObject) {
		
		this.image=new Image("RedBall.png");
		
		CircleShape shape = new CircleShape();
		
		r=image.getWidth()/2;
		
		if(mapObject.getProperty("radius")!=null){
			r=Integer.valueOf(mapObject.getProperty("radius"));
		}

		shape.m_radius = (r-3)/Game.PIXEL_PER_METER;
		
		FixtureDef fixtureDef = new FixtureDef();
		fixtureDef.shape = shape;
		fixtureDef.restitution = 0.6f;
		fixtureDef.friction=0.0f;
		
		
		BodyDef bodyDef = new BodyDef();
		bodyDef.type = BodyType.DYNAMIC;
		bodyDef.position.set(mapObject.getX()/Game.PIXEL_PER_METER,mapObject.getY()/Game.PIXEL_PER_METER);
		body = world.createBody(bodyDef);
		body.createFixture(fixtureDef);
		body.m_angularDamping=0.3f;
		body.m_linearDamping=0.3f;
		
	}

	Image image;
	
	public void render(Context2d context) {
		body.setAngularVelocity((float) (Math.random()*0.1f)); // otherwise balls hangs on some corners

		ImageElement element = ImageElement.as(image.getElement());

		Vec2 position = body.getPosition();
		
		int x = (int) (position.x*Game.PIXEL_PER_METER)-r;
		int y = (int) (position.y*Game.PIXEL_PER_METER)-r;
		
		context.drawImage(element, x, y, r*2, r*2);
	}

}
